package com.wehealth;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.wehealth.dm.User;
import com.wehealth.util.DataManger;
import com.wehealth.util.GetUrl;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Personal_Info_modify extends Fragment{

	private static final int NET_ERROR = -100;
	private MainActivity mConext;
	private TextView userAccount;
	private EditText userNameEt;
	private TextView userSexEt;
	private EditText userAgeEt;
	private EditText userPhoneNumEt;
	private EditText userAddersEt;
	private User user;
	private User muser;
	private static  String JSONResult;
	private String userName;
	private String sex ;
	private String age ;
	private String phonum;
	private String address;
	private int  sexIndex = 0;
	private DataManger mDataMange;
	private AlertDialog dialog;
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		
		mConext =(MainActivity)getActivity();
		mDataMange = mConext.getDataManger();
		TextView title=(TextView)mConext.findViewById(R.id.header_title);
		String titlename = mConext.getString(R.string.person_modify_title);
		title.setText(titlename);
		int color =mConext.getResources().getColor(R.color.text_color_green);
		title.setTextColor(color);

		 Button bBack = (Button) mConext.findViewById(R.id.header_bBack);
		 bBack.setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{		
					mConext.switchContentHome();
				}
			});
		 
		    user =mConext.getUserInfo();
		    muser = new User();
		    muser.setAccount(user.getAccount());
		    
		    TextView mLoginNameTv =(TextView)mConext.findViewById(R.id.person_modify_name);
		    String mLoginName = mLoginNameTv.getText()+user.getAccount();
		    mLoginNameTv.setText(mLoginName);
		    
		    Button modifySubmitBt = (Button)mConext.findViewById(R.id.modify_submit_bt);
		    modifySubmitBt.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					RegistToConnServer();
				}
			});
		    
		    
			userNameEt = (EditText)mConext.findViewById(R.id.person_modify_user_name_et);;
			userSexEt = (TextView)mConext.findViewById(R.id.person_modify_sex_tx);
			userSexEt.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					openSelectSexDialog();
				}
			});
			userAgeEt = (EditText)mConext.findViewById(R.id.person_modify_age_et);;
			userPhoneNumEt =(EditText)mConext.findViewById(R.id.person_modify_phonenumber_et);;
			userAddersEt =(EditText)mConext.findViewById(R.id.person_modify_address_et);;
		    
	
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		 return  inflater.inflate(R.layout.personal_info_modify, null);
	}
	
	
	private void openSelectSexDialog(){
		 AlertDialog.Builder builder = new AlertDialog.Builder(mConext); 
		   builder.setIcon(null);
		   builder.setTitle(null);
		   builder.setNegativeButton("女", new AlertDialog.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				String   sex = getString(R.string.register_user_sex_women);
				userSexEt.setText(sex);
				sexIndex =1;
			}
		});
		   
		    builder.setPositiveButton("男", new AlertDialog.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					String   sex = getString(R.string.register_user_sex_man);
					userSexEt.setText(sex);
					sexIndex =0;
				}  	
		    });
		    
		    builder.create().show();
		
	}
	
	
	private void RegistToConnServer(){
        new Thread(){
            @Override
            public void run(){
                try {
                            initDataFromNetPersonInfoModify();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Message message = new Message();
                message.what = 0;
                handler.sendMessage(message);
            }
            }.start();
	}
	
	private void initDataFromNetPersonInfoModify() throws IOException{
		 userName = userNameEt.getText().toString().trim();
		 age = userAgeEt.getText().toString().trim();
		 phonum=userPhoneNumEt.getText().toString().trim();
		 address=userAddersEt.getText().toString().trim();
		
	     String urlAPI = GetUrl.GetPersonInfoModify_Url();
	     HttpPost httpRequest= new HttpPost(urlAPI);
	     List <NameValuePair> params = new ArrayList <NameValuePair>();
	     String ID =String.valueOf(user.getUserId());
	     params.add(new BasicNameValuePair("userID",ID));
	     params.add(new BasicNameValuePair("realName",userName));
	     String sex;
	     if(sexIndex==0){
	       sex = getString(R.string.register_user_sex_man);
	      }else{
	       sex = getString(R.string.register_user_sex_women);
	      }
	     params.add(new BasicNameValuePair("sex",sex));
	     //String age =String.valueOf(user.getUserAge());
	     params.add(new BasicNameValuePair("age",age));
	     params.add(new BasicNameValuePair("password",null));
	     params.add(new BasicNameValuePair("phone",phonum));
	     
	     try{
	         httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
	         HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
	         if(httpResponse.getStatusLine().getStatusCode() == 200)
	         {
	             JSONResult = EntityUtils.toString(httpResponse.getEntity());
	             Log.d("SIMMON:", "JSONResult="+JSONResult);
	         }
	     } catch(Exception e){
	         Log.e("SIMMON:",  e.toString());
	     }

	}

	private Handler handler =new Handler(){
	    @Override
	    public void handleMessage(Message msg){
	        super.handleMessage(msg);
	        //mProgress.setVisibility(View.GONE);
	       switch (msg.what) {
	            case 0:
	                if(JSONResult!=null){
	                    BindNewsData(JSONResult);
	                }else{
	                    //mProgress.setVisibility(View.GONE);
	                	openModifyDialog(NET_ERROR);
	                    }
	              break;
	            default:
	                break;
	        }
	    }
	};
	    
	
	private void BindNewsData(String strJSON){
	    try{
	            JSONObject jsonObject = new JSONObject(strJSON);
	            String result_str = jsonObject.getString("result");
	            Log.d("SIMMON"," result_str="+result_str);
	            int result = Integer.valueOf(result_str);
	            Log.d("SIMMON"," result="+result);
	            openModifyDialog(result);
	            
	    }catch(JSONException ex)
	    {
	            Log.e("JSON Error: ", ex.toString()); 
	    }
	    
	}
	
	private void openModifyDialog(final int result){
		   String login_result = mConext.getString(R.string.regist_fail);
		     Log.d("SIMMON","######result  ="+result);
	       switch (result) {
	       case -3:
	           login_result = getString(R.string.regist_phone_num_fail);
	           break;
	       case -2:
	           login_result = getString(R.string.regist_fail3);
	           break;
	       case -1:
	           login_result = getString(R.string.regist_fail);
	           break;
	       case 0:
	           login_result = getString(R.string.regist_fail2);
	           break;
	       case NET_ERROR:
	           login_result = getString(R.string.net_connet_fail);
	           break;
	       default:
	           if(result > 0){
	               login_result = getString(R.string.regist_success);
	               user.setPhoneNumber(phonum);
	               int ageInt =Integer.valueOf(age);
	               user.setUserAge(ageInt);
	               user.setUserSex(sexIndex);
	               user.setUserName(userName);
	               user.setaddress(address);
	               mDataMange.delUserDate();
	               mDataMange.storeUserInfo(user);
	           }else{
	               login_result =getString(R.string.regist_fail);
	           }
	           break;
	   }

		     AlertDialog.Builder builder = new AlertDialog.Builder(mConext); 
		        View view = LayoutInflater.from(mConext).inflate(R.layout.dialog_self_viewbt,null);
		        TextView textview = (TextView)view.findViewById(R.id.dialog_self_tx);
		        textview.setText(login_result);
		        Button okBt =(Button)view.findViewById(R.id.dialog_self_bt);
		        String okBtBtStr ="确定";
		        okBt.setText(okBtBtStr);
		        okBt.setOnClickListener(new OnClickListener() {
		           
		           @Override
		           public void onClick(View arg0) {
		               // TODO Auto-generated method stub
		               if(result > 0){
                           Home vHome = new Home();
                           mConext.switchContent(vHome);           
		                   }
		               dialog.cancel();
		           }
		       });
		        builder.setView(view);
		        dialog=  builder.create();
		        dialog.show();
		}
	
	

}
